package cn.com.cetccst.distribution.business.message;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;

import cn.com.cetccst.datacenter.message.InboxMessageRespository;
import cn.com.cetccst.datacenter.message.entity.InboxMessageEntity;

//企业内部console下发的消息
public class EnterpriseMessage implements IMessage {

    protected static int CONTENT_MAX_LENGTH = 128;
    protected static int SUBJECT_MAX_LENGTH = 16;

    public static final String FIELD_MSG_CNT = "noticeContent";

    protected JSONObject rootJson;

    public EnterpriseMessage(JSONObject rootJson) {
        this.rootJson = rootJson;
    }

    @Override
    public void parse(Context context) {
        String msgCnt = rootJson.optString(FIELD_MSG_CNT);

        InboxMessageEntity inboxMessage = new InboxMessageEntity();
        inboxMessage.setAppId(context.getPackageName());
        inboxMessage.setTitle(getMyAppName(context));
        JSONObject msgCntJson = null;
        try {
            msgCntJson = new JSONObject(msgCnt);
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }
        inboxMessage.setContent(subString(msgCntJson.optString("content"), CONTENT_MAX_LENGTH));
        inboxMessage.setSubject(subString(msgCntJson.optString("title"), SUBJECT_MAX_LENGTH));

        inboxMessage.setRead(0);

        long receivedTime = System.currentTimeMillis();
        if (msgCntJson.optLong("time") > 0) {
            receivedTime = msgCntJson.optLong("time");
        }
        inboxMessage.setReceivedDate(receivedTime);
        InboxMessageRespository.getInstance().saveMessage(inboxMessage);
    }

    public static String subString(String string, int length) {
        if (!TextUtils.isEmpty(string) && string.length() > length) {
            return string.substring(0, length);
        }
        return string;
    }

    public static String getMyAppName(Context context) {
        PackageInfo packageInfo = null;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
        }
        return packageInfo != null ? packageInfo.applicationInfo.loadLabel(context.getPackageManager()).toString() : "";
    }
}